// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 云函数入口函数
exports.main = async (event, context) => {
  // 加入班级
  const db = cloud.database()
  const _ = db.command
  // 班级id
  const { id, name, avatar, identification } = event
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID

  const member = { name, avatar, identification, openid }
  
  await db.collection('class').doc(id).update({
    data: {
      members: _.push([ member ])
    }
  })

  // 往平时分库中加入一条初始记录
  await db.collection('score').add({
    data: {
      class_id: id,
      name,
      identification,
      avatar,
      openid,
      score: 0
    }
  })
}